
// 将多维数据转化为一维
export function flatten(list = []) {
    let res = [];
    list.forEach((item) => {
        res.push(item);
        res = res.concat(flatten(item.children));
    });
    return res;
}
// 元素全屏
export function enterFullscreen(ele = document.documentElement) {
    if (ele.requestFullscreen) {
        ele.requestFullscreen();
    } else if (ele.mozRequestFullScreen) {
        ele.mozRequestFullScreen();
    } else if (ele.webkitRequestFullscreen) {
        ele.webkitRequestFullscreen();
    } else if (ele.msRequestFullscreen) {
        ele.msRequestFullscreen();
    }
}
export function exitFullscreen() {
    if (document.exitFullScreen) {
        document.exitFullScreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    }
}
export function isFullscreen() {
    return !!(
        document.fullscreenElement ||
        document.msFullscreenElement ||
        document.mozFullScreenElement ||
        document.webkitFullscreenElement ||
        false
    );
}
export function debounce(fn, wait = 1000) {
    let timer;
    return function () {
        let context = this;
        let args = arguments;
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(context, args);
        }, wait)
    }
}
// 获取自研播放器授权参数
export function getMetaPlayerConfig() {
    let path = window.location.origin;
    let pathname = window.location.pathname;
    path = path + pathname.substring(0, pathname.lastIndexOf('/'));
    // qiankun微应用下libpath指向当前微应用的根路径
    if (window.__POWERED_BY_QIANKUN__) {
        path = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
        path = path.substring(0, path.lastIndexOf('/')); // 去除末尾的斜杠
    }
    // 方式一：全部读取本地json文件
    // 测试环境、开发环境
    return {
        path: path,
        authUrl:
            window.location.origin +
            window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')),
        appId: process.env.NODE_ENV === 'development' ? 'f3429e' : 'b4e0c9'
    };
}

// 简单封装接口请求，统一处理报错提示和请求头参数
export function requestApi({ url, method = 'get', data = {}, headers = {} }) {
  if (!window.wgt) {
    // wgt.showMessage({
    //   title: '缺少wgt环境',
    //   icon: 'error',
    //   duration: 3000
    // })
    return Promise.reject('缺少wgt环境');
  }
  return wgt.request({
    url: url,
    method: method,
    data: data,
    headers
  }).then(res => {
    const { code, msg } = res || {};
    if (code !== 0) {
        // 针对大屏编辑特殊处理
        if (!['dv.dlife.cn'].includes(window.location.host)) {
            wgt.showMessage({
                title: msg || '接口请求出错，请稍后重试',
                icon: 'error',
                duration: 3000
            })
        }
    }
    return res;
  }).catch(err => {
    console.log('接口调用异常1', err);
    wgt.showMessage({
      title: err.message,
      icon: 'error',
      duration: 3000
    })
    return err;
  })
}

/**
 * 
 * @param {Object} props 卡片$props参数
 * @param {String} props.card 卡片基础信息，JSON.parse解析后含screenId(所在大屏id),appId(卡片id),index(卡片索引)
 * @param {String} props.config 卡片业务传参，JSON.parse解析后一般含isPub(是否公共大屏),roleId(角色id),roleType(角色类型),accessToken(业务token)
 * @param {Object} otherOptions 其他配置项，如cardName
 */
export function formatCardProps(props, otherOptions = {}) {
    let propCard = JSON.parse(props.card||'{}'),
      propConfig = JSON.parse(props.config||'{}'),
      propSize = JSON.parse(props.size||'{}');
    return {
      screenId: propCard.screenId,
      cardId: propCard.appId,
      index: propCard.index,
      isPub: propConfig.isPub,
      userId: propConfig.userId,
      roleId: propConfig.roleId,
      roleType: propConfig.roleType,
      accessToken: propConfig.accessToken,
      cardName: otherOptions.cardName,
      width: propSize.width,
      height: propSize.height
    }
}

/**
 * 将px单位转化为rem单位
 * @param {*} val px输入值，支持数组形式，仅转化带'px'单位的值
 * @param {*} remRootValue 转为rem的基础字体大小，卡片默认值为192
 */
export function pxToRem(val, remRootValue = 192) {
    // console.log('pxToRem-input', val);
    if(Array.isArray(val)) {
        return val.map(it => this.pxToRem(it));
    }
    val = '' + val;
    // 单位不含px，直接返回
    if(val.indexOf('px') === -1) return val;
    let res = val.replace(/(\d+)px/g, function(a, b) {
        let num = b / remRootValue + '';
        return num.substring(0, 7) + 'rem';
    })
    // console.log('pxToRem-output', res);
    return res;
}

/**
 * js动画
 * @param {Number} duration 动画间隔(ms)
 * @param {Number} from 变化起始值
 * @param {Number} to 变化目标值
 * @param {Function} onProgress 值变化回调处理函数
 */
export function myAnimatiton(duration = 1000, from = 0, to = 0, onProgress = () => {}) {
    try {
        const dis = to - from,
            speed = dis / duration,
            startTime = Date.now();
        let value = from;
        onProgress(value);

        function _run() {
            const now = Date.now();
            const time = now - startTime;
            if(time >= duration) {
                value = to;
                onProgress(value);
                return;
            }
            const d = time * speed;
            value = from + d;
            onProgress(value);
            requestAnimationFrame(_run);
        }

        requestAnimationFrame(_run);
    } catch(e) {
        console.log(e);
        return;
    }
}

/**
 * 判断一个变量是否为对象（不包含数组、null）
 * @param {*} variable 要判断的变量
 * @returns 
 */
export function isObject(variable) {
    return typeof variable === 'object' && variable !== null && !Array.isArray(variable);
}